package com.iot.lemon.util;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.iot.lemon.model.SysUser;
import com.iot.lemon.model.TVillage;
import com.iot.lemon.service.SysUserService;
import com.iot.lemon.service.TVillageService;

import top.ibase4j.core.Constants;
import top.ibase4j.core.exception.BusinessException;
import top.ibase4j.core.support.context.ApplicationContextHolder;
import top.ibase4j.core.support.http.SessionUser;
import top.ibase4j.core.util.CacheUtil;
import top.ibase4j.core.util.InstanceUtil;
import top.ibase4j.core.util.MathUtil;
import top.ibase4j.core.util.WebUtil;

/**
 * @author ShenHuaJie
 * @since 2018年8月31日 下午9:30:04
 */
public class UserUtil {
    private static Logger logger = LogManager.getLogger();

    public static Long getMyOrgaId(HttpServletRequest request) {
        SessionUser sessionUser = WebUtil.getCurrentUser(request);
        Long userId = sessionUser.getId();
        String key = Constants.CACHE_NAMESPACE + "MYORGID:" + userId;
        Long orgId = null;
        try {
            orgId = (Long)CacheUtil.getCache().get(key);
        } catch (Exception e) {
            logger.error("", e);
        }
        if (orgId == null) {
            SysUser sysUser = ApplicationContextHolder.getBean(SysUserService.class).queryById(userId);
            orgId = sysUser.getOrgaId();
            CacheUtil.getCache().set(key, orgId, random());
        }
        return orgId;
    }

    public static List<Long> getMyOrgIds(HttpServletRequest request) {
        SessionUser sessionUser = WebUtil.getCurrentUser(request);
        Long userId = sessionUser.getId();
        String key = Constants.CACHE_NAMESPACE + "MYORGIDS:" + userId;
        List<Long> orgIds = null;
        try {
            orgIds = JSON.parseArray((String)CacheUtil.getCache().get(key), Long.class);
        } catch (Exception e) {
            logger.error("", e);
        }
        if (orgIds == null) {
            SysUser sysUser = ApplicationContextHolder.getBean(SysUserService.class).queryById(userId);
            orgIds = sysUser.getOrgaIds();
            CacheUtil.getCache().set(key, JSON.toJSONString(orgIds), random());
        }
        return orgIds;
    }

    /**
     * 获取用户所在小区
     * @return
     */
    public static Long getMyVillageId(HttpServletRequest request) {
        SessionUser sessionUser = WebUtil.getCurrentUser(request);
        Long userId = sessionUser.getId();
        String key = Constants.CACHE_NAMESPACE + "MYVILLAGEID:" + userId;
        Long villageId = null;
        try {
            villageId = (Long)CacheUtil.getCache().get(key);
        } catch (Exception e) {
            logger.error("", e);
        }
        if (villageId == null) {
            Map<String, Object> params = InstanceUtil.newHashMap("managerId", userId);
            List<TVillage> list = ApplicationContextHolder.getBean(TVillageService.class).queryList(params);
            if (list.isEmpty()) {
                throw new BusinessException("只有小区管理员可以进行该操作.");
            }
            villageId = list.get(0).getId();
            CacheUtil.getCache().set(key, villageId, random());
        }
        return villageId;
    }

    private static int random() {
        return MathUtil.getRandom(60, 300).intValue();
    }
}
